<?php

namespace wxpay;


class Wxtransfer
{


    public function pay($openid, $money, $desc = '')
    {
        $params["mch_appid"] = 'wxe4b77d2f0f456b9b';
        $params["mchid"] = '1601872738';
        $params["nonce_str"] = $this->createNoncestr();
        $params["partner_trade_no"] = date('YmdHis') . rand(1000, 9999);
        $params["amount"] = 100 * ($money);
        $params["desc"] = $desc;
        $params["openid"] = $openid;
        $params["check_name"] = 'NO_CHECK';
        $params['spbill_create_ip'] = '';

//        $key = 'GDDGxnm0769qweASDzxc889966774412';//API密码
        $secrect_key = 'GDDGxnm0769qweASDzxc889966774412';//API密码
        $data = array_filter($params);
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $str .= 'key=' . $secrect_key;
        $data['sign'] = md5($str);
        //生成签名
//        $str = 'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].'&mch_appid='.$params["mch_appid"].'&mchid='.$params["mchid"].'&nonce_str='.$params["nonce_str"].'&openid='.$params["openid"].'&partner_trade_no='.$params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key='.$key;

        //md5加密 转换成大写
        $sign = strtoupper(md5($str));
        //生成签名
        $params['sign'] = $sign;

        //构造XML数据
        $xmldata = $this->array_to_xml($params); //数组转XML
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        //发送post请求
        $res = $this->curl_post_ssl($url, $xmldata); //curl请求
        if (!$res) {
            return array('status' => 1,
                'msg' => "服务器连接失败");
        }

        //付款结果分析
        $content = $this->xml_to_array($res); //xml转数组
        return json_encode($content);
    }

    public function pro_pay($openid = '', $money = 0, $desc = '')
    {
        $money = '0.1';//测试
        $params["mch_appid"] = 'wxf8b5cc76a8fa700b';//小程序打款
        $params["mchid"] = '1601872738';
        $params["nonce_str"] = $this->createNoncestr();
        $params["partner_trade_no"] = date('YmdHis') . rand(1000, 9999);
        $params["amount"] = 100 * ($money);
        $params["desc"] = $desc;
        $params["openid"] = $openid;
        $params["check_name"] = 'NO_CHECK';
        $params['spbill_create_ip'] = '';

//        $key = 'GDDGxnm0769qweASDzxc889966774412';//API密码
        $secrect_key = 'GDDGxnm0769qweASDzxc889966774412';//API密码
        $data = array_filter($params);
        ksort($data);
        $str = '';
        foreach ($data as $k => $v) {
            $str .= $k . '=' . $v . '&';
        }
        $str .= 'key=' . $secrect_key;
        $data['sign'] = md5($str);
        //生成签名
//        $str = 'amount='.$params["amount"].'&check_name='.$params["check_name"].'&desc='.$params["desc"].'&mch_appid='.$params["mch_appid"].'&mchid='.$params["mchid"].'&nonce_str='.$params["nonce_str"].'&openid='.$params["openid"].'&partner_trade_no='.$params["partner_trade_no"].'&spbill_create_ip='.$params['spbill_create_ip'].'&key='.$key;

        //md5加密 转换成大写
        $sign = strtoupper(md5($str));
        //生成签名
        $params['sign'] = $sign;

        //构造XML数据
        $xmldata = $this->array_to_xml($params); //数组转XML
        $url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers';

        //发送post请求
        $res = $this->curl_post_ssl($url, $xmldata); //curl请求
        if (!$res) {
            return array('status' => 1,
                'msg' => "服务器连接失败");
        }

        //付款结果分析
        $content = $this->xml_to_array($res); //xml转数组
        return json_encode($content);
    }

    public function createNoncestr($length = 32)
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }


    public function curl_post_ssl($url, $xmldata, $second = 30, $aHeader = array())
    {
        $ch = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        //绝对地址可使用 dirname(__DIR__)打印，如果不是绝对地址会报 58 错误
        curl_setopt($ch, CURLOPT_SSLCERT, './cert_transfer/apiclient_cert.pem');
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, './cert_transfer/apiclient_key.pem');
        if (count($aHeader) >= 1) {
            curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
        }
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xmldata);
        $data = curl_exec($ch);
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            echo "call faild, errorCode:$error\n";
            die();
            curl_close($ch);
            return false;
        }
    }

    /**
     * array 转 xml
     * 用于生成签名
     */
    public function array_to_xml($arr)
    {
        $xml = "<xml>";
        foreach ($arr as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
        }
        $xml .= "</xml>";
        return $xml;
    }

    /**
     * xml 转化为array
     */
    public function xml_to_array($xml)
    {
        //禁止引用外部xml实体
        libxml_disable_entity_loader(true);
        $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $values;
    }


}
